package app.gui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.io.IOException;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

import app.Main;
import app.conn.WebDB;


public class RegisterDialog extends JDialog {
	private JTextField nameField;
	private JPasswordField passField;
	private JPasswordField passField2;
	private JCheckBox saveUser;
	
	private boolean save = false;

	public RegisterDialog(Frame parent) {
		super(parent, "Vytvoření nového účtu", true);
		
		save = Main.appcnf.isSavelogin();

		JPanel panel = new JPanel(new GridBagLayout());
		GridBagConstraints cs = new GridBagConstraints();

		cs.fill = GridBagConstraints.HORIZONTAL;
		cs.insets = new Insets(10, 10, 0, 10);

		cs.gridx = 0;
		cs.gridy = 0;
		cs.gridwidth = 1;
		panel.add(new JLabel("Uživatelské jméno: "), cs);

		nameField = new JTextField(20);
		nameField.addKeyListener(new EnterListener());
		if(Main.appcnf.getName() != null) {
			nameField.setText(Main.appcnf.getName());
		}
		cs.gridx = 1;
		cs.gridy = 0;
		cs.gridwidth = 2;
		panel.add(nameField, cs);

		cs.gridx = 0;
		cs.gridy = 1;
		cs.gridwidth = 1;
		panel.add(new JLabel("Heslo: "), cs);

		passField = new JPasswordField(20);
		passField.addKeyListener(new EnterListener());
		cs.gridx = 1;
		cs.gridy = 1;
		cs.gridwidth = 2;
		panel.add(passField, cs);

		cs.gridx = 0;
		cs.gridy = 2;
		cs.gridwidth = 1;
		panel.add(new JLabel("Opakovat heslo: "), cs);

		passField2 = new JPasswordField(20);
		passField2.addKeyListener(new EnterListener());
		cs.gridx = 1;
		cs.gridy = 2;
		cs.gridwidth = 2;
		panel.add(passField2, cs);

		saveUser = new JCheckBox("Uložit přihlašovací údaje");
		saveUser.setSelected(save);
		saveUser.addItemListener(new ChcboxSaveListener());
		cs.gridx = 1;
		cs.gridy = 3;
		cs.gridwidth = 2;
		panel.add(saveUser, cs);

		JPanel buttons = new JPanel(new FlowLayout(FlowLayout.TRAILING));
		
		JButton butLogin = new JButton("Přejít k přihlášení");
		butLogin.addActionListener(new ButLoginListener());
		buttons.add(butLogin);		

		JButton butCancel = new JButton("Storno");
		butCancel.addActionListener(new ButCancelListener());
		buttons.add(butCancel);
		
		JButton butOK = new JButton("Registrovat");
		butOK.addActionListener(new ButOKListener());
		buttons.add(butOK);
		
		this.add(panel, BorderLayout.CENTER);
		this.add(buttons, BorderLayout.PAGE_END);

		pack();
		setResizable(false);
		setLocationRelativeTo(parent);
		setVisible(true);
	}

	private class ButOKListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent arg0) {
			String name = nameField.getText();

			/* verify user name policy */
			if(name.length() > 0 && name.length() < 65) {
				for(int i = 0; i < name.length(); i++) {
					if(!Character.isDigit(name.charAt(i)) && !Character.isLetter(name.charAt(i))) {
						Main.showError("Chybné uživatelské jméno", "Jméno obsahuje neplatné znaky");
						return;
					}
				}
			}
			else {
				Main.showError("Chybné uživatelské jméno", "Uživatelské jméno musí mít délku mezi 1 - 64 znaků");
				return;
			}

			/* verify password policy */
			String password = String.valueOf(passField.getPassword());

			if(password.length() < 5) {
				Main.showError("Chybné heslo", "Heslo musí obsahovat minimálně 5 znaků");
				return;
			}
			if(!String.valueOf(passField.getPassword()).equals(password)) {
				Main.showError("Chybné heslo", "Zadaná hesla se neshodují");
				return;
			}

			/* send register request */
			try {
				Main.setToken(WebDB.register(name, password), name);
				
				// null token returned - access denied
				if(!Main.isLogged()) {
					Main.showError("Chyba přihlášení", "Neplatné uživatelské jméno nebo heslo");
				}
			} catch (IOException e) {
				Main.showError("Chyba připojení", "Nelze se připojit k vzdálené databázi");
				dispose();
				return;
			}
			MainFrame.getInstance().status.setText("Uživatel: ".concat(nameField.getText()));
			MainFrame.getInstance().enableRemotePanel(true);
			
			/* user registration successfully acomplished */
			if(save) {
				Main.appcnf.setName(name);
				Main.appcnf.setToken(Main.getToken());
				Main.appcnf.save();
			}
			
			dispose();
		}

	}

	private class ButCancelListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent arg0) {
			dispose();

		}

	}
	
	private class ButLoginListener implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			dispose();
			new LoginDialog(MainFrame.getInstance());
		}
		
	}
	
	private class ChcboxSaveListener implements ItemListener {

		@Override
		public void itemStateChanged(ItemEvent e) {
			if(e.getStateChange() == ItemEvent.SELECTED) {
				save = true;
			}
			else {
				save = false;
			}
			Main.appcnf.setSavelogin(save);
			Main.appcnf.save();
		}
		
	}
	
	/**
	 * Key Listener
	 * - Enter -> OK button pressed
	 * 
	 * @author Lukas Vavra
	 *
	 */
	private class EnterListener implements KeyListener {
		@Override
		public void keyPressed(KeyEvent e) {
			if(e.getKeyCode() == KeyEvent.VK_ENTER) {
				new ButOKListener().actionPerformed(null);
			}
		}

		@Override
		public void keyReleased(KeyEvent e) {}

		@Override
		public void keyTyped(KeyEvent e) {}
		
	}
}
